//
// Created by Tian on 25-5-2.
//
#include "stdint.h"
#include "lcd_support.h"
#include "lcd_spi.h"
#include "driver/gpio.h"

#define LCD_RES_GPIO_PIN 13
#define LCD_DC_GPIO_PIN  12
#define LCD_BLK_GPIO_PIN 10

#define LCD_RES_Set() gpio_set_level(LCD_RES_GPIO_PIN, 1)
#define LCD_RES_Clr() gpio_set_level(LCD_RES_GPIO_PIN, 0)

#define LCD_DC_Set() gpio_set_level(LCD_DC_GPIO_PIN, 1)
#define LCD_DC_Clr() gpio_set_level(LCD_DC_GPIO_PIN, 0)

#define LCD_BLK_Set() gpio_set_level(LCD_BLK_GPIO_PIN, 1)
#define LCD_BLK_Clr() gpio_set_level(LCD_BLK_GPIO_PIN, 0)



void lcd_basic_io_init(void)
{
    gpio_config_t gpio_init_struct = {0};
    gpio_init_struct.intr_type = GPIO_INTR_DISABLE;           /* 失能引脚中断 */
    gpio_init_struct.mode = GPIO_MODE_INPUT_OUTPUT;           /* 输入输出模式 */
    gpio_init_struct.pull_up_en = GPIO_PULLUP_ENABLE;         /* 使能上拉 */
    gpio_init_struct.pull_down_en = GPIO_PULLDOWN_DISABLE;    /* 失能下拉 */
    gpio_init_struct.pin_bit_mask = 1ull << LCD_RES_GPIO_PIN |  \
                                    1ull << LCD_DC_GPIO_PIN  |  \
                                    1ull << LCD_BLK_GPIO_PIN; /* 设置的引脚的位掩码 */
    gpio_config(&gpio_init_struct);                           /* 配置GPIO */
}

void lcd_set_backlight(int state)
{
    if (state)
    {
        gpio_set_level(LCD_BLK_GPIO_PIN, 1);
    }
    else {
        gpio_set_level(LCD_BLK_GPIO_PIN, 0);
    }
}

void lcd_set_dc(int sta)
{
    if(sta)
    {
        gpio_set_level(LCD_DC_GPIO_PIN, 1);
    }
    else{
        gpio_set_level(LCD_DC_GPIO_PIN, 0);
    }
}

void lcd_set_rst(int sta)
{
    if(sta)
    {
        gpio_set_level(LCD_RES_GPIO_PIN, 1);
    }
    else{
        gpio_set_level(LCD_RES_GPIO_PIN, 0);
    }

}
/**
 * @brief       向液晶写寄存器命令
 * @param       reg: 要写的命令
 * @retval      无
 */
void LCD_WR_REG(uint8_t reg)
{
    LCD_DC_Clr();
    bsp_spi_write_byte( reg);
    LCD_DC_Set();
}

/**
 * @brief       向液晶写一个字节数据
 * @param       dat: 要写的数据
 * @retval      无
 */
void LCD_WR_Byte(uint8_t dat)
{
    LCD_DC_Set();
    bsp_spi_write_byte( dat);
    LCD_DC_Clr();
}


/**
 * @brief       向液晶写一个半字数据
 * @param       dat: 要写的数据
 * @retval      无
 */
void LCD_WR_HalfWord(uint16_t dat)
{
    LCD_DC_Set();
    uint8_t dat_buff[2];
    dat_buff[0] = dat >> 8;
    dat_buff[1] = dat & 0xff;
    bsp_spi_write_data(2,dat_buff );
//    bsp_spi_write_byte(lcd_spi_handle, dat >> 8);
//    bsp_spi_write_byte(lcd_spi_handle, dat & 0xFF);
    LCD_DC_Clr();
}

/**
 * @brief       向液晶连续写入len个字节数据
 * @param       dat: 要写的数据地址
 * @param       len：要写入字节长度
 * @retval      无
 */
void LCD_WR_DATA(int len, const uint8_t *dat )
{
    LCD_DC_Set();
    bsp_spi_write_data(len, dat);
    LCD_DC_Clr();
}

void spi_send_cmd(uint8_t reg, uint8_t len, uint8_t* arg)
{
    LCD_DC_Clr();
    bsp_spi_write_byte( reg);
    LCD_DC_Set();
    bsp_spi_write_data(len, arg);
}

